﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using System.Text.RegularExpressions;
using System.Data;
using System.Data.SqlClient;
using System.Net.Mail;
using System.Net.Mime;
using System.IO;
using System.Security.Cryptography;
using System.Web.Security;
using SQLExecute;


/// <summary>
/// Summary description for User
/// </summary>
public class User
{
	public User()
	{
		//
		// TODO: Add constructor logic here
		//
	}

    private DataSet ds;
    private int _id;


    private string _fullname;
    private string _username;
    private string _password;
    private string _email;

    public int ID
    {
        set { _id = value; }
        get { return _id; }
    }
    public string FullName
    {
        set { _fullname = value; }
        get { return _fullname; }
    }
    public string UserName
    {
        set { _username = value; }
        get { return _username; }
    }
    public string Password
    {
        set { _password = value; }
        get { return _password; }
    }
    public string Email
    {
        set { _email = value; }
        get { return _email; }
    }

    public bool checkLogin(string u, string p)
    {

        ds = SqlHelper.ExecuteDataset(Common.strConnect, "Check_Login", new object[] { u, p });

        if (ds.Tables[0].Rows.Count > 0)
        {
            this._id = Convert.ToInt16(ds.Tables[0].Rows[0]["id"].ToString());
            this._fullname = ds.Tables[0].Rows[0]["fullname"].ToString();
            this._username = ds.Tables[0].Rows[0]["username"].ToString();
            this._email = ds.Tables[0].Rows[0]["email"].ToString();
            
            return true;
        }

        else return false;
    }

    public DataSet Get_List_Users()
    {
        //string sql = "select id, fullname, username,group_name,date_created from tbl_users";

        ds = SqlHelper.ExecuteDataset(Common.strConnect, "Get_List_Users");


        return ds;
    }

    public DataSet Get_Group_Users()
    {


        ds = SqlHelper.ExecuteDataset(Common.strConnect, "Get_List_Group_User");

        return ds;
    }
    public int Insert_New_User(string pass,bool active)
    {


        int i=SqlHelper.ExecuteNonQuery(Common.strConnect, "Insert_New_User", new object[] {_fullname, _username, pass,_email,DateTime.Now.ToShortDateString(), active });

       return i;
    }
    public string Get_IPAddress()
    {
       

       string strIPAddress = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
       
       //string strHostName = System.Net.Dns.GetHostEntry(strIPAddress).HostName;
       string strHostName = HttpContext.Current.Request.UserHostName.ToString();

       //_pcname = strHostName;


       return strHostName + " - " + strIPAddress;

        

    
    }
    public DataSet Get_List_Users(string c)
    {

        ds = SqlHelper.ExecuteDataset(Common.strConnect, "Get_List_Users", new object[] { c});

        return ds;    
    }
    public void Update_Password()
    {

        SqlHelper.ExecuteNonQuery(Common.strConnect, "Change_Pass", new object[] { _id, Encrypt_Pass()});

    }
    public bool ValidMail(string s)
    {
        Regex regEmail = new Regex(@"^[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]@[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]$");
        if (regEmail.IsMatch(s))
            return true;
        else return false;
    }
    public bool EmailExist()
    {
        string sql = "select id,fullname,username, email from tbl_users where email='" + _email + "'";
        SqlDataReader r;

        r = SqlHelper.ExecuteReader(Common.strConnect, CommandType.Text, sql);
        if (r.HasRows)
        {
            while (r.Read())
            {
                _id = Convert.ToInt16(r[0].ToString());
                _fullname = r[1].ToString();
                _username = r[2].ToString();


            }

            r.Close();
            return true;
        }

        else

            return false;
    }
    public string RandomPassword()
    {
       
        Guid id = new Guid();
        id = Guid.NewGuid();
        _password = id.ToString();
        _password = _password.Substring(0, 6);

        return _password;
    }
    public string Encrypt_Pass()
    {

        UnicodeEncoding encoding = new UnicodeEncoding();
        Byte[] hashBytes = encoding.GetBytes(_password);
        // Compute the SHA-1  hash
        SHA1CryptoServiceProvider sha1 = new SHA1CryptoServiceProvider();
        Byte[] cryptPassword = sha1.ComputeHash(hashBytes);

        return BitConverter.ToString(cryptPassword);

    }
    public void SendMail(string from,string to,string subject,int nCaseForSendMail)
    {

        string strMessageBody;
        string strLogo = string.Empty;
        AlternateView alternateView;
        StreamReader streamReader = null;

        //doc file template html
        if (nCaseForSendMail == 1)//new user
        {
            streamReader = new StreamReader(HttpContext.Current.Server.MapPath("~/mail/mail_new_user.htm"));
            streamReader = File.OpenText(HttpContext.Current.Server.MapPath("~/mail/mail_new_user.htm"));
            
        }
        else if (nCaseForSendMail == 2)//forgot password
        {
            streamReader = new StreamReader(HttpContext.Current.Server.MapPath("~/mail/mail_forgot_password.htm"));
            streamReader = File.OpenText(HttpContext.Current.Server.MapPath("~/mail/mail_new_user.htm"));
            
        }

        string strContentHtml = streamReader.ReadToEnd();
        streamReader.Close();

        //thay cac thong tin can thiet
        strMessageBody = strContentHtml.Replace("<Ten_Ung_Vien>", this._fullname);
        strMessageBody = strMessageBody.Replace("<username>", this._username);
        strMessageBody = strMessageBody.Replace("<password>", this._password);
        strMessageBody = strMessageBody.Replace("<image logo here>", "<img src=cid:imgLogo />");

        strLogo = HttpContext.Current.Server.MapPath(@"../images/logo.png");
        LinkedResource logo = new LinkedResource(strLogo);
        logo.ContentId = "imgLogo";
        ContentType mimeType = new System.Net.Mime.ContentType("text/html");
        alternateView = AlternateView.CreateAlternateViewFromString(strMessageBody, mimeType);

        alternateView.LinkedResources.Add(logo);

        System.Net.Mail.MailMessage mailMessage = new System.Net.Mail.MailMessage(from, to);
        mailMessage.AlternateViews.Add(alternateView);
        mailMessage.Body = strMessageBody;

        mailMessage.IsBodyHtml = true;
        mailMessage.Subject = subject;
        SmtpClient s = new SmtpClient("192.168.0.100");
        s.Send(mailMessage);


    }

}
